package event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @program: javaLearn
 * @description: 倒计时
 * @author: renhai
 * @Date ：2021/12/24 15:40
 **/
public class clock extends JFrame implements ActionListener, Runnable {
    int count = 60;
    JButton start;
    JButton stop;
    JLabel time;
    Thread t1;

    public clock() {
        super("时钟倒计时！");
        FlowLayout fl = new FlowLayout(FlowLayout.CENTER);
        this.setLayout(fl);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(400, 400, 400, 400);
        start = new JButton("开始");
        stop = new JButton("暂停");
        time = new JLabel("60");
        this.add(start);
        this.add(time);
        this.add(stop);
        start.addActionListener(this);
        stop.addActionListener(this);
        t1 = new Thread(this);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == start) {
            t1 = new Thread(this);
            t1.start();
        } else if (e.getSource() == stop) {
            t1.interrupt();
        }
    }

    public static void main(String[] args) {
        new clock();
    }

    @Override
    public void run() {
        while (count > 0 && t1.isAlive() && !t1.isInterrupted()) {
            count--;
            time.setText(count + "秒");
            try {
                t1.sleep(1000);
            } catch (Exception e) {
                break;
            }
        }
    }
}
